package com.hnqc.wukoy;
import javax.swing.*;

import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {

    private DefaultListModel dt;
    private JTextArea jta;
    private JTextField jtf_message = new JTextField(30);
    private JTextField jtf_port = new JTextField("3245");
    private JTextField jtf_max = new JTextField("30");
    private JButton jbt_start = new JButton("启动");
    private JButton jbt_stop = new JButton("停止");
    private List<Socket> list= new ArrayList<Socket>();
    private List<User> listuser= new ArrayList<User>();
    String name=null;

    public void createUI(){
        JFrame jf = new JFrame("服务器");
        jf.setBounds(200,200,500,300);

        JPanel northPane = new JPanel();
        northPane.setLayout(new GridLayout(1,6));
        northPane.add(new JLabel("人数上限"));
        northPane.add(jtf_max);
        northPane.add(new JLabel("端口"));
        northPane.add(jtf_port);
        northPane.add(jbt_start);
        jbt_stop.setEnabled(false);
        northPane.add(jbt_stop);
        northPane.setBorder(new TitledBorder("配置信息"));

        dt = new DefaultListModel();
        JList jl = new JList(dt);
        JScrollPane leftpane = new JScrollPane(jl);
        leftpane.setBorder(new TitledBorder("在线用户"));

        jta = new JTextArea();
        jta.setEnabled(false);
        JScrollPane reghtpane = new JScrollPane(jta);
        reghtpane.setBorder(new TitledBorder("消息显示区"));
        JSplitPane centPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,leftpane,reghtpane);

        centPane.setDividerSize(20);
        centPane.setDividerLocation(100);

        JPanel southPanel = new JPanel();
        southPanel.setBorder(new TitledBorder("写消息"));
        southPanel.add(jtf_message,BorderLayout.CENTER );
        jf.setLayout(new BorderLayout());
        jf.add(northPane,BorderLayout.NORTH);
        jf.add(centPane,BorderLayout.CENTER);
        jf.add(southPanel,BorderLayout.SOUTH);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
        myEvent();
    }

    private void myEvent() {
        jtf_message.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {

                if (e.getKeyChar() == KeyEvent.VK_ENTER) {

                    for (Socket s : list) {
                        try {
                            OutputStream out = s.getOutputStream();

                            //PrintWriter pw = new PrintWriter(out);
                            PrintWriter pw = new PrintWriter(out, true);
                            pw.println(jtf_message.getText().trim());
                            pw.flush();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                    jtf_message.setText("");
                }
            }
        });

        jbt_start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String port = jtf_port.getText().trim();
                int port_new = Integer.parseInt(port);
                try {
                    final ServerSocket ss = new ServerSocket(9999);
                    System.out.println("在监听中....");

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            while (true) {
                                Socket socket = null;
                                try {

                                    socket = ss.accept();
                                    list.add(socket);
                                    //服务器读一次
//                                    InputStream inputStream = socket.getInputStream();
//                                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
//                                    String s = bufferedReader.readLine();
//                                    System.out.println(s);
//                                    String[] strings = s.split(",");
//                                    String name=strings[0];
//                                    String ip=strings[1];
//                                    String port=strings[2];
//                                    User user1=new User(name,ip,port);
//                                    listuser.add(user1);
                                    Socket finalSocket = socket;

                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            while (true) {
                                                try {
                                                    InputStream inputStream = finalSocket.getInputStream();
                                                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                                                    String s = bufferedReader.readLine();
                                                    String[]strings= s.split(",");
                                                    name=strings[0];
                                                    String ip=strings[1];
                                                    String port=strings[2];
                                                    User user=new User(name,ip,port);
                                                    listuser.add(user);
                                                    dt.addElement(name);

//                                                  PrintStream printStream=new PrintStream(finalSocket.getOutputStream());
//                                                  printStream.println(listuser);listuser



                                                } catch (IOException e1) {
                                                    e1.printStackTrace();
                                                }

                                            }

                                        }
                                    }).start();


//                                    Server.ReaderThread readerThread = new Server.ReaderThread(socket);
//                                    new Thread(readerThread).start();
//                                    System.out.println("Connected...This Port\n" + socket.getPort());
//                                    System.out.println("Get success...This IP\n" + socket.getInetAddress());
                                } catch (IOException e1) {
                                    e1.printStackTrace();
                                }

                            }
                        }
                    }).start();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    class ReaderThread implements Runnable{
        private  Socket socket;
        public ReaderThread(Socket socket){
            this.socket=socket;
        }
        @Override
        public void run() {
            try {
                InputStream in=socket.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
                while (true){
                    String str=bufferedReader.readLine();
                    jta.append("用户："+str+"\n");

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new Server().createUI();
    }
}




